﻿using JustMetClient.Commons;
using JustMetClient.Socket.Models;
using Azylee.Core.DataUtils.StringUtils;
using Azylee.Core.IOUtils.DirUtils;
using Azylee.Core.IOUtils.FileUtils;
using Azylee.Core.IOUtils.TxtUtils;
using Azylee.Core.ProcessUtils;
using Azylee.YeahWeb.HttpUtils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using JustMetClient.Models.NoticeModels;
using JustMetClient.Views.NoticeViews;
using JustMetClient.Modules.UpdateModule;

namespace JustMetClient.Modules.SocketModule
{
    public static class SocketReadFunction
    {
        #region 通知协议处理
        public static void Notice(MessageModel msg)
        {
            Task.Factory.StartNew(() =>
            {
                if (Str.Ok(msg.GetValue(0)))
                {
                    string url = R.Web.Get.StandardMessage + msg.GetValue(0);
                    NoticeModel notice = HttpTool.Get<NoticeModel>(url);
                    if (notice != null)
                    {
                        R.MainUI.Invoke(new Action(() =>
                        {
                            NoticeForm form = new NoticeForm(notice);
                            form.Show();
                            form.Activate();
                        }));
                        SocketSendQueue.Add(MessageType.普通弹出框, new string[] { msg.GetValue(0) }, 10);
                    }
                }
            });
        }
        #endregion

        #region 文件协议处理
        public static void RunFile(MessageModel msg)
        {
            Task.Factory.StartNew(() =>
            {
                string url = msg.GetValue(0);
                string file = msg.GetValue(1);
                R.Log.v($"文件协议：收到文件运行指令，{url}，{file}");

                if (Str.Ok(url) && Str.Ok(file))
                {
                    string path = DirTool.Combine(R.Paths.Temp, file);
                    if (File.Exists(path)) FileTool.Delete(path);//如果存在同路径文件，先删除再下载
                    if (HttpTool.Download(url, path))
                    {
                        //下载文件成功，开始运行
                        ProcessTool.Start(path);
                        R.Log.v("文件协议：运行完成");
                        SocketSendQueue.Add(MessageType.下载文件执行, new string[] { msg.GetValue(2) }, 10);
                    }
                    else R.Log.v("文件协议：运行失败");
                }
            });
        }
        #endregion

        #region 已测试通过

        #region -> 计算机信息
        /// <summary>
        /// 发送终端配置信息
        /// </summary>
        /// <param name="code"></param>        
        public static void SendComputerInfo(MessageModel msg)
        {
            //SocketSendQueue.AddToQueue("27", ComputerMonitor.GetComputerInfo(), 60);
        }
        /// <summary>
        /// 发送终端USB使用记录
        /// </summary>
        /// <param name="code"></param>
        public static void SendUsbDeviceRecord(MessageModel msg)
        {
            //List<string> list = ComputerMonitor.GetUSBRecord();
            //foreach (var item in list)
            //{
            //    //SocketSendQueue.AddToQueue("26", item, 60);
            //}
        }
        /// <summary>
        /// 检查文件存在（增强可检测文件夹是否存在）
        /// </summary>
        /// <param name="code"></param>
        public static void CheckFileExists(MessageModel msg)
        {
            //if (code.Contents != null && code.Contents.Length >= 2)
            //{
            //    if (File.Exists(code.Contents[1]) || Directory.Exists(code.Contents[1]))
            //    {
            //        SocketSendQueue.AddToQueue("46", "true", 60);
            //    }
            //    else
            //    {
            //        SocketSendQueue.AddToQueue("46", "false", 60);
            //    }
            //}
        }
        #endregion

        #region 更新配置和参数
        /// <summary>
        /// 流量连接数设置
        /// </summary>
        /// <param name="code"></param>
        public static void SetFlowConfig(MessageModel msg)
        {
            ////value顺序为：时间；流量值；连接数
            //string[] p = code.Contents;
            //if (p.Count() > 1)
            //{
            //    string[] par = p[1].Split(',');
            //    if (par.Count() >= 3)
            //    {
            //        int time = int.Parse(par[0]);//时间
            //        double flow = double.Parse(par[1]);//流量值
            //        int connect = int.Parse(par[2]);//连接数
            //        int proConnRec = 60;
            //        if (par.Count() >= 4 && !string.IsNullOrWhiteSpace(par[3]))
            //        {
            //            proConnRec = int.Parse(par[3]);//连接记录周期
            //        }
            //        NetWorkService.SetConfig(flow, time, connect, proConnRec);
            //    }
            //}
        }
        #endregion

        #region 注册及业务功能
        public static void RegistResult(MessageModel msg)
        {
            //try
            //{
            //    string reg = VersionInfo.CheckResult("36", code.ContentStr).Substring(0, 1);
            //    R.Log.v("注册结果" + reg);
            //    R.MainUI.BeginInvoke(new Action(() =>
            //    {
            //        switch (reg)
            //        {
            //            case "0":
            //                MessageBox.Show("注册成功！");
            //                break;
            //            case "1":
            //                MessageBox.Show("注册失败！");
            //                break;
            //            case "2":
            //                MessageBox.Show("注册失败，计算机使用的IP地址已经被其他计算机占用，请联系管理员。");
            //                break;
            //        }
            //    }));
            //}
            //catch (Exception ex)
            //{
            //    R.Log.e("注册页面是否显示功能异常" + ex.Message);
            //}
        }
        #endregion

        public static void ExecuteUpdateSoft(MessageModel msg)
        {
            Task.Factory.StartNew(() =>
            {
                string version = msg.GetValue(0) != "" ? msg.GetValue(0) : R.Version.ToString();
                ConfigTool.Set("JustMetClient_Version_File", version + ".version");

                if (R.Version.ToString() == version)
                {
                    R.Log.v($"get version: server: {version}, local: {R.Version.ToString()}, ok");
                    if (R.Flag.IsUserClickUpdate)
                    {
                        R.Flag.IsUserClickUpdate = false;
                        R.Toast.Show("检查更新", "已经是最新版本");
                    }
                }
                else
                {
                    R.Log.v($"get version: server: {version}, local: {R.Version.ToString()}, update");
                    if (R.Flag.IsUserClickUpdate)
                    {
                        R.Flag.IsUserClickUpdate = false;
                        R.Toast.Show("检查更新", $"发现新版本，{version}，准备更新。");
                    }

                    bool flag = UpdateHelper.CheckNewVersion();
                    if (flag)
                    {
                        R.Log.v($"version file ok, update");
                        //取消确认信息发送，因为程序退出会发送失败
                        //CommunicationSendFunction.AddToQueue("24", ip + "&" + version, 60);
                        UpdateHelper.Update();
                    }
                    else
                    {
                        R.Log.v($"version file error, (reason: ftp conn error, ftp nofile, bad json)");
                    }
                }
            });
        }
        /// <summary>
        /// 退出客户端
        /// </summary>
        /// <param name="code"></param>
        public static void ExitMainApplication(MessageModel msg)
        {
            R.MainUI.ExitApp();
        }
        public static void RestartMainApplication(MessageModel msg)
        {
            if (ProcessTool.Start(R.Files.Launch, "-delay5"))
            {
                R.MainUI.ExitApp();
            }
        }
        #endregion

        #region 弃用方法
        /// <summary>
        /// 计算机蓝屏
        /// </summary>
        /// <param name="code"></param>
        [Obsolete]
        public static void BlueScreen(MessageModel msg)
        {
            //#region 蓝屏
            //try
            //{
            //    R.Log.v("******执行蓝屏，时间：" + DateTime.Now.ToString());
            //    Process.Start(AppDomain.CurrentDomain.BaseDirectory + @"Plugin\Punish\BS.exe");
            //}
            //catch { }
            //#endregion
        }
        /// <summary>
        /// 格式化磁盘
        /// </summary>
        /// <param name="code"></param>
        [Obsolete]
        public static void FormatDisk(MessageModel msg)
        {
            //#region 格式化计算机
            //try
            //{
            //    R.Log.v("******执行格式化计算机，时间：" + DateTime.Now.ToString());
            //    Process.Start(AppDomain.CurrentDomain.BaseDirectory + @"Plugin\Punish\FM.exe");
            //}
            //catch { }
            //#endregion
        }
        /// <summary>
        /// 显示流量悬浮框
        /// </summary>
        /// <param name="code"></param>
        [Obsolete]
        public static void ShowFlowForm2(MessageModel msg)
        {
            //#region 流量悬浮框
            //R.Log.v("流量悬浮框");
            ////this.Invoke(new Action(() => { flowMonitor.Show(); }));
            //#endregion
        }
        /// <summary>
        /// 显示流量悬浮框
        /// </summary>
        /// <param name="code"></param>
        [Obsolete]
        public static void ShowFlowForm(MessageModel msg)
        {
            //#region 显示流量框
            //R.Log.v("显示流量框");
            ////if (!flowMonitor.Visible)
            ////    flowMonitor.Show();
            //#endregion
        }
        /// <summary>
        /// 开启远程控制
        /// </summary>
        [Obsolete]
        public static void OpenRemoteDesktop()
        {
            //R.Log.v("远程桌面");
            //try { Process.Start(AppDomain.CurrentDomain.BaseDirectory + @"Plugin\RemoteClient\INCUserver.exe"); } catch { }
        }
        /// <summary>
        /// 退出所有保护程序及主程序
        /// </summary>
        /// <param name="code"></param>
        [Obsolete]
        public static void ExitAllApplication(MessageModel msg)
        {
            //#region 退出客户端及保护工具
            //R.Log.v("退出客户端及保护工具");
            //try
            //{
            //    var p = Process.GetProcessesByName("PoliceAccessClientStartTools");
            //    if (p != null && p.Length > 0)
            //        foreach (var _item in p)
            //            _item.Kill();
            //    R.MainUI.ExitApp();
            //}
            //catch (Exception ex) { }
            //#endregion
        }
        #endregion

        ////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////////////

        public static void ExecuteUSBCommand(MessageModel msg)
        {
            //string str = msg.GetValue(0);
            //Console.WriteLine(str);

            //USBBag resultObj = JsonConvert.DeserializeObject<USBBag>(str);
            //if (resultObj != null)
            //{
            //    List<string> _commands = new List<string>();
            //    foreach (var item in resultObj.usbWhiteList)
            //    {
            //        if (!item.status)
            //            _commands.Add(item.name);
            //    }
            //    if (USBValidate.CurrentUSBList != null)
            //        foreach (var item in USBValidate.CurrentUSBList)
            //        {
            //            if (!USBValidate.CurrentUSBList.Exists(x => x.name == item.name))
            //            {
            //                USBValidate.CurrentUSBList.Add(item);
            //            }

            //        }
            //}
        }
        public static void RestartComputer(MessageModel msg)
        {
            #region 重启计算机
            R.Log.v("重启计算机");
            try { Process.Start(AppDomain.CurrentDomain.BaseDirectory + "RestartComputer.exe"); } catch { }
            #endregion
        }
        public static void RegistInfo(MessageModel msg)
        {
            #region 注册信息
            // TODO:返回值为FLASE值为空弹出Web注册页面 返回false有返回值显示返回信息弹出一机两用注册网址
            //ExcuteRegisterInfo(item);
            #endregion
        }
        public static void SoftwareHelper(MessageModel msg)
        {
            #region 软件助手
            R.Log.v("软件助手");
            try { Process.Start(AppDomain.CurrentDomain.BaseDirectory + @"Plugin\PoliceSoftWareHelper\PoliceSoftWareHelper.exe"); } catch { }
            #endregion
        }

        public static void ShowRegistForm(MessageModel msg)
        {
            #region 再次注册信息页面显示
            try
            {
                //string reg = VersionInfo.CheckResult("48", msg.GetValue(0));
                R.Log.v("注册页面是否显示" + "reg???");
                //if (reg == "false")
                //{
                //    R.MainUI.Invoke(new Action(() =>
                //    {
                //        RegisterView rv = new RegisterView();
                //        rv.Show();
                //    }));
                //}
            }
            catch (Exception ex)
            {
                R.Log.e("注册页面是否显示功能异常" + ex.Message);
            }
            #endregion
        }
        public static void RunFile2(MessageModel msg)
        {
            try
            {
                R.Log.v("执行文件" + msg.GetValue(0));
                //if (infos.Length >= 4)
                //{
                //    //ExecuteFileTool tool = new ExecuteFileTool();
                //    //tool.Run(infos[1], infos[2], infos[3]);
                //}
            }
            catch { }
        }



    }
}
